<template>
  <div class="container">
    <div class="app-containerP">
      <div class="leftP">
        <el-container>
        </el-container>
        <el-table
          ref="resTable"
          :data="depts"
          highlight-current-row
          @current-change="selectNode"
          :cell-style="cellStyle"
          height="500px"
        >
          <el-table-column
            property="secondmentName"
            label="事项名称"
            width="150px">
          </el-table-column>
          <el-table-column
            property="departmentName"
            label="创建部门"
            width="150px">
          </el-table-column>
          <el-table-column
            property="createTime"
            label="创建时间"
            width="150px">
          </el-table-column>
        </el-table>
      </div>
      <div class="rightP">
        <el-row class="opeate-tools" type="flex" justify="start">
          <el-button size="mini" @click="exportResponseFile">导出全部文件</el-button>
          <el-button size="mini" @click="showPdfDialog = true" v-if="visible()">上传请示pdf</el-button>
          <el-button size="mini" @click="changeSecondmentState" v-if="visible()">上报</el-button>

          <el-date-picker
            style="margin-left:4px"
            v-if="confirmVisible()"
            type="date"
            value-format="yyyy-MM-dd"
            v-model="secondmentDate"
            placeholder="请选择借调起始时间">
          </el-date-picker>
          <el-date-picker
            style="margin-left:4px"
            v-if="confirmVisible()"
            type="date"
            value-format="yyyy-MM-dd"
            v-model="endTime"
            placeholder="请选择借调结束时间">
          </el-date-picker>
          <el-button size="mini"   v-if="confirmVisible()" @click="confirmTime()" round>确认时间</el-button>
          <!--<el-button size="mini" @click="" v-if="confirmVisible()">上传审核pdf</el-button>-->
          <el-upload
            style="width: 100px; height: 30px;margin-left:10px;margin-top:2px"
            v-if="confirmVisible()"
            class="upload-demo"
            :http-request="handleBeforeUpload2"
            action=""
            :file-list="fileList"
            :show-file-list="false"
          >
            <el-button size="small" type="primary">借调命令</el-button>
          </el-upload>
        </el-row>
        <!-- 表格组件 -->
        <el-scrollbar style="width: 1000px;">
          <el-table :data="bdMap">
            <!-- 这是header部分 -->
            <el-table-column label="部门名称" property="departmentName" width="400px">
            </el-table-column>
            <!-- header -->
            <!-- body部分 -->
            <el-table-column label="操作" width="600px">
              <template v-slot="{ row }" style=" display: flex;">
                <div class="operation-flex-container">
                  <el-tag :type="getResponseType(row)">{{ row.responseState }}</el-tag>
                  <el-button :disabled="row.responseState !== '已上报'" slot="reference" style="margin-left:10px"
                             type="text"
                             @click="dRes(row)"
                  >下载回函
                  </el-button>
                  <el-select
                    style="width: 100px; height: 50px;margin-left:10px;"
                    v-if="(row.responseState == '已上报')"
                    :disabled="!confirmVisible()"
                    @change="handleConfirmChange(row)"
                    placeholder="请选择"
                    v-model="row.confirm"
                  >
                    <el-option
                      label="审核通过"
                      value="审核通过"
                    ></el-option>
                    <el-option
                      label="驳回"
                      value="驳回"
                    ></el-option>
                  </el-select>
                  <!--<el-button size="mini" @click="" style="width: 100px; height: 50px;margin-left:10px;" v-if="confirmVisible()&&(row.responseState == '已上报')" round>上传审核pdf</el-button>-->
                  <el-upload
                    style="width: 100px; height: 50px;margin-left:10px;margin-top:10px"
                    v-if="confirmVisible()&&(row.responseState == '已上报')"
                    class="upload-demo"
                    action=""
                    :http-request="handleBeforeUpload"
                    :show-file-list="false"
                    :file-list="fileList"
                  >
                    <el-button size="small" type="primary" @click="setCurrentRow(row)">借调命令</el-button>
                  </el-upload>
                </div>
              </template>
            </el-table-column>
            <!-- body部分 -->
          </el-table>
        </el-scrollbar>

        <!-- 分页 -->
        <el-row style="height: 60px;" align="middle" type="flex" justify="center">
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            :current-page="queryParams.pageNum"
            :page-size="queryParams.pageSize"
            @current-change="changePage"
          />
        </el-row>
        <import-pdf :show-pdf-dialog.sync="showPdfDialog" @uploadSuccess="alertInfo"/>
      </div>
    </div>
    <!-- 放置导入组件 -->
  </div>
</template>

<script>
  import {geSecondment} from '@/api/department'
  import {confirmTime} from '@/api/role'
  import {
    getResponseDepartment,
    getResponseZipFile,
    getZipName,
    changeSecondmentState,
    dowRes,
    changeConfirmState
  } from '@/api/role'
  import FileSaver from 'file-saver'
  import store from '@/store'
  import ImportPdf from './components/import-pdf.vue'
  import {oneDepartmentConfirmSecondment,allDepartmentConfirmSecondment,getResponsePdfName} from '@/api/employee'
  import { MessageBox } from 'element-ui';
  export default {
    name: 'role',
    components: {
      ImportPdf
    },
    data() {
      return {
        depts: [], // 组织数据
        // 存储查询参数
        queryParams: {
          secondmentId: null,
          pageNum: 1, // 当前页码
          pageSize: 10,
        },
        inputContent: '', // 借调事项名称
        total: 0, // 记录员工的总数
        bdMap: [],
        currentUserId: null, // 用来记录当前点击的用户id
        distributeChildValue: '', // 传递给子组件的值
        childId: '',
        showPdfDialog: false,
        fileList: [],
        currentRow: {},
        secondmentDate: null,
        secondmentLastTime: null,
        endTime: null,
      }
    },
    created() {
      this.geSecondment()
    },
    methods: {
      setCurrentRow(row) {
        this.currentRow = row;
      },
      confirmTime(){
        const data = {
          secondmentId : this.queryParams.secondmentId,
          secondmentDate: this.secondmentDate,
          endTime: this.endTime,
        }
        try {
           confirmTime(data)
          console.log("confirm"+data.secondmentDate)
        } catch (error) {
          this.$message.error('确认时间错误');
        } finally {
        }
      },
      handleBeforeUpload(param) {
        const depart = {};
        depart.departmentId = this.currentRow.departmentId
        depart.secondmentId = this.currentRow.secondmentId
        const data = new FormData()
        data.append('file', param.file);
        data.append('secondmentId', depart.secondmentId)
        data.append('departmentId', depart.departmentId)
        console.log("depart"+depart)
        try {
          const response = oneDepartmentConfirmSecondment(data);
          console.log("response" + response);
          // 成功
          this.$message.success('上传成功！')

        } catch (error) {
          this.$message.error('文件上传发生错误');
        } finally {
        }

    },
    handleBeforeUpload2(param) {
      console.log("param" + param.file)
      const secondmentId = this.queryParams.secondmentId
      // this.uploadFileToServer2(param.file);

      console.log("param" + param.file)
      // 大于0 说明有文件要上传
      const data = new FormData()
      // file: file类型
      // data.append('file', files[0]) // 将文件参数加入到formData中
      // 遍历文件列表
      // for (let i = 0; i < param.file.length; i++) {
      //   // 使用 'file' + i 作为键名，以区分多个文件
      //   data.append('files', param.file[i]);
      // }
      data.append('file', param.file);
      data.append('secondmentId', secondmentId)
      try {
        console.log("data" + data)
        const response = allDepartmentConfirmSecondment(data);
        console.log("response" + response);
        // 成功
        this.$message.success('上传成功！')

      } catch (error) {
        this.$message.error('文件上传发生错误');
      } finally {
      }

      // console.log(param.file)
      // 阻止自动上传
      // return false;
    },

    // async handleConfirmChange(row) {
    //   const data = {};
    //   data.departmentId = row.departmentId
    //   data.secondmentId = row.secondmentId
    //   data.departmentName = row.departmentName
    //   data.confirm = row.confirm
    //   await changeConfirmState(data)
    // },
      async handleConfirmChange(row) {
        const confirmValue = row.confirm; // 获取当前选择的值

        if (confirmValue === '审核通过' || confirmValue === '驳回') {
          try {
            await MessageBox.confirm('确定要进行此操作吗？‌', '确认', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            });

            // 用户确认后的操作
            const data = {
              departmentId: row.departmentId,
              secondmentId: row.secondmentId,
              departmentName: row.departmentName,
              confirm: confirmValue,
            };

            await changeConfirmState(data); // 调用异步函数处理数据

            // 如果需要，‌可以在这里处理函数返回的结果或进行其他操作
          } catch (error) {
            // 用户取消操作或MessageBox.confirm抛出错误
            console.error('用户取消或发生错误:', error);
            // 可以选择恢复下拉框的值或其他操作
          }finally {
            await this.getResponseDepartment()
          }
        }
      },
    async geSecondment() {
      const data = {
        departmentId: store.getters.departmentId,
        levelId: store.getters.levelId,
        departmentName: store.getters.name
      }
      this.depts = await geSecondment(data)
      this.queryParams.secondmentId = this.depts[0].id
      //this.getResponseDepartment()
      this.$nextTick(() => {
        const firstRowOfFirstTable = this.$refs.resTable.$el.querySelector('.el-table__body tbody tr');
        if (firstRowOfFirstTable) {
          firstRowOfFirstTable.click(); // 模拟点击第一行
        }
      });
    },
    async getResponseDepartment() {
      const {responseVOList, total} = await getResponseDepartment(this.queryParams)
      this.bdMap = responseVOList
      this.total = total
      //this.responseType
    },
    selectNode(node) {
      this.queryParams.secondmentId = node.id // 重新记录了参数
      this.queryParams.pageNum = 1 // 设置第一页
      this.getResponseDepartment()
      this.secondmentDate=null
      this.endTime=null
    },
    // 切换页码
    changePage(newPage) {
      this.queryParams.pageNum = newPage // 赋值新页码
      //this.getBodyList() // 查询数据
      this.getResponseDepartment()
    },
    /** *
     * 导出所有文件
     *
     * **/
    async exportResponseFile() {
      const result = await getResponseZipFile(this.queryParams.secondmentId)
      const name = await getZipName(this.queryParams.secondmentId)
      const zipName = name + '.zip'
      FileSaver.saveAs(result, zipName)
    },
    getResponseType(row) {
      if (row.responseState == '未上报') {
        return 'danger'
      } else {
        return 'success'
      }
    },
    async changeSecondmentState() {
      await changeSecondmentState(this.queryParams.secondmentId)
      this.$message.success('上报成功！')
    },
    alertInfo() {
      this.$message.success('上传成功！')
    },
    visible() {
      if (store.getters.levelId === 1) {
        return false
      }
      return true
    },
    confirmVisible() {
      if (store.getters.levelId === 1) {
        return true
      }
      return false
    },
    cellStyle() {
      return "cursor:pointer;"
    },
    async dRes(row) {
      const data = {
        departmentId: row.departmentId,
        secondmentId: row.secondmentId
      }
      const f = await dowRes(data)
      const name = await getResponsePdfName(data)
      // FileSaver.saveAs(f, row.responseFileName)
      if (name.includes(';')) {
        FileSaver.saveAs(f, "部门回函.zip")
      } else {

        FileSaver.saveAs(f, name)
      }
    }
  }
  }
</script>

<style lang="scss" scoped>
  .operation-flex-container {
    display: flex;
    align-items: center; /* 垂直居中 */
  }

  .app-containerP {
    background: #fff;
    display: flex;
    .leftP {
      width: 320px;
      padding: 20px;
      border-right: 1px solid #eaeef4;
    }
    .rightP {
      flex: 1;
      padding: 20px;
      .opeate-tools {
        margin: 10px;
      }
      .opeate-tools > .el-button {
        border-radius: 5px;
        border-color: rgb(55, 55, 55);
        color: rgb(35, 35, 35);
      }
    }
  }
</style>
